#ifndef __MYTHREAD_HPP__
#define __MYTHREAD_HPP__

#include <iostream>
#include <pthread.h>
#include <functional>
#include <string>

namespace Mythread
{
	template <class T>
	using func_t = std::function<void(T &, std::string &)>;

	template <class T>
	class Thread
	{
	public:
		void Excute()
		{
			_func(_data,_threadname);
		}

	public:
		Thread(func_t<T> func, T &data, std::string &name = "none-name")
			: _func(func), _data(data), _threadname(name), _stop(true)
		{
		}

		static void *threadroutine(void *args) // 类成员函数，形参是有this指针的！
		{
			Thread<T> *self = static_cast<Thread<T> *>(args);
			self->Excute();
			return nullptr;
		}

		bool start()
		{
			int n = pthread_create(&_tid, nullptr, threadroutine, this);
			if (!n)
			{
				_stop = false;
				return true;
			}
			else
			{
				return false;
			}
		}

		bool join()
		{
			if (!_stop)
			{
				pthread_join(_tid, nullptr);
			}

			return true;
		}

		void detach()
		{
			if (!_stop)
			{
				pthread_detach(_tid);
			}
		}

		std::string name()
		{
			return _threadname;
		}

		void stop()
		{
			_stop = true;
		}

		~Thread() {}

	private:
		pthread_t _tid;			 // 线程id
		std::string _threadname; // 线程名
		T &_data;				 // 数据
		func_t<T> _func;		 // 执行任务
		bool _stop;				 // 启动状态
	};
}

#endif